package springmvc.high.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * description: 拦截器
 *
 * 1. 实现接口 HandlerInterceptor
 * 2. 方法 preHandle() 执行Handler之前调用的方法，用于设置编码格式、登录保护、权限处理等。返回 true 放行，false 拦截。
 * 3. 方法 postHandle() Handler执行完毕后调用的方法，用于对结果处理、敏感词汇检查。
 * 4. 方法 afterCompletion() 整体处理完毕后执行，渲染视图之后执行,一定执行
 */

public class MyInterceptor implements HandlerInterceptor {

    /**
     * @param request 请求对象
     * @param response 响应对象
     * @param handler handler 要调用的方法对象
     * @return true放行，false拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor.preHandle");
        return true;
    }

    /**
     * @param request 请求
     * @param response 响应
     * @param handler handler方法
     * @param modelAndView 返回的视图和共享域数据对象
     * (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor.postHandle");
    }

    /**
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous=
     * @param ex  handler报错异常对象
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor.afterCompletion");
    }
}
